package com.company.prototype;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 原型模式-深拷贝
 */
public class CarByDeep implements Serializable {

    //名称
    private String name;
    //车长
    private int length;
    //包含型号
    private List<String> modelList = new ArrayList<>();


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public List<String> getModelList() {
        return modelList;
    }

    public void setModelList(List<String> modelList) {
        this.modelList = modelList;
    }


    /**
     * 深拷贝
     * @return
     */
    public Object deepClone() {
        try {
            //输出序列化
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);

            //输入反序列化
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            CarByDeep copyObj = (CarByDeep) ois.readObject();

            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
